package com.zcurd.account.common.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jfinal.handler.Handler;
import com.zcurd.common.util.UrlUtil;

public class LoginHandler extends Handler{

	@Override
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		HttpSession session = request.getSession();
		
		String currUrl = UrlUtil.formatUrl(request.getRequestURI());
		String contextPath = request.getContextPath();
		//排除登陆页面和res目录
		if(!currUrl.endsWith("/login") && !currUrl.endsWith("/login/randomCode") && !currUrl.startsWith(contextPath + "/res")) {
			//如果session为空表示用户没有登录就重定向到login页面
			if(session.getAttribute("sysUser") == null) {
				try {
					response.sendRedirect(request.getContextPath() + "/login");
				} catch (IOException e) {
					e.printStackTrace();
				}
				return;
			}
			
			//首页跳转到main页面
			if(currUrl.equals(contextPath) || currUrl.equals(contextPath + "/index")) {
				try {
					response.sendRedirect(request.getContextPath() + "/main");
				} catch (IOException e) {
					e.printStackTrace();
				}
				return;
			}
		}
		next.handle(target, request, response, isHandled);
	}

}
